//
//  ZSHotSellingCopywritingViewController.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/10.
//

import UIKit
import ProgressHUD

class ZSHotSellingCopywritingViewController: ZSBaseViewController {

    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var themTextFiled: UITextField!
    @IBOutlet weak var communeTextField: UITextField!
    @IBOutlet weak var styleButton: UIButton!
    @IBOutlet weak var unlimitedButton: UIButton!
    @IBOutlet weak var fiveHundredButton: UIButton!
    @IBOutlet weak var eightHundredButton: UIButton!
    @IBOutlet weak var customNumberTextField: UITextField!
    @IBOutlet weak var tagSwitch: UISwitch!
    @IBOutlet weak var modelEssaySwitch: UISwitch!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var contentTextView: UITextView!
    @IBOutlet weak var placeholderLabel: UILabel!
    
    var styles: [String] = [
        "无限制",
        "教程类",
        "评测类",
        "生活方式分享",
        "用户故事",
        "合集类",
        "高级感",
        "校园风",
        "氛围感",
        "职场生活",
        "低脂低卡",
        "露营徒步",
        "自律生活",
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }
    
    fileprivate func setupViews() {
        view.backgroundColor = UIColor(hexString: "#F0F3FD")
        navigationHeight.constant = UIApplication.shared.statusBarFrame.size.height + 44
        customNumberTextField.delegate = self
        contentTextView.delegate = self
    }
    
    @IBAction func goBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func didSelectStyle(_ sender: UIButton) {
        self.view.endEditing(true)
        if self.styles.count == 0 { return }
        let alertController = UIAlertController(title: "请选择文章风格", message: "", preferredStyle: .actionSheet)
        self.styles.forEach { title in
            let action = UIAlertAction(title: title, style: .default) { (action) in
                self.styleButton.setTitle(title, for: .normal)
                self.styleButton.setTitleColor(UIColor(hexString: "#222222"), for: .normal)
            }
            alertController.addAction(action)
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
        }
        alertController.addAction(cancelAction)
        present(alertController, animated: true, completion: nil)
    }
    
    @IBAction func didSelectTextNumber(_ sender: UIButton) {
        if sender.isSelected { return }
        sender.isSelected = !sender.isSelected
        customNumberTextField.text = ""
        if sender == unlimitedButton {
            fiveHundredButton.isSelected = false
            eightHundredButton.isSelected = false
        }else if sender == fiveHundredButton {
            unlimitedButton.isSelected = false
            eightHundredButton.isSelected = false
        }else if sender == eightHundredButton {
            unlimitedButton.isSelected = false
            fiveHundredButton.isSelected = false
        }
    }
    
    @IBAction func didSelectTagSwitch(_ sender: UISwitch) {
        
    }
    
    @IBAction func didSelectModelEssaySwitch(_ sender: UISwitch) {
        contentView.isHidden = !sender.isOn
    }
    
    @IBAction func didCopy(_ sender: UIButton) {
        if let text = UIPasteboard.general.string {
            contentTextView.text = text
        }
    }
    
    @IBAction func goCreation(_ sender: Any) {
        guard let theme = themTextFiled.text, !theme.isEmpty else {
            self.view.makeToast("请输入创作主题", position: .center)
            return
        }
        var content =  "帮我围绕主题【\(theme)】创作一篇小红书爆文，"
        if let commune = communeTextField.text, !commune.isEmpty {
            content = content + "目标受众是【\(commune)】，"
        }
        
        if let style = styleButton.titleLabel?.text, !style.isEmpty {
            content = content + "文章风格为【\(style)】，"
        }
        if modelEssaySwitch.isOn {
            content = content + "参考范文如下：【\(contentTextView.text ?? "")】"
        }
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbmajiabao/api/wenxinyiyan/chat"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
       let parameters: [String: Any] = [
            "messages": [
                [
                    "role": "user",
                    "content": content
                ]
            ]
        ]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                self.view.makeToast("创作失败，请重试！", duration: 1.0, position: .center)
                print("Error: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let dict = json["data"] as? [String: Any], let result = dict["result"] as? String, !result.isEmpty {
                    DispatchQueue.main.async {
                        let vc = ZSCreationResultsViewController()
                        vc.template = content
                        vc.content = result
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            } catch {
                self.view.makeToast("创作失败，请重试！", duration: 1.0, position: .center)
                print("Error parsing JSON: \(error)")
            }
        }
        task.resume()
    }
}

extension ZSHotSellingCopywritingViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        if let text = textField.text, !text.isEmpty {
            unlimitedButton.isSelected = false
            fiveHundredButton.isSelected = false
            eightHundredButton.isSelected = false
        }
    }
}

extension ZSHotSellingCopywritingViewController: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        placeholderLabel.isHidden = true
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
}
